<template>
  <lay-layer
    v-model="visible"
    title="订单详情"
    :area="['90%', '90%']"
    :max-width="1200"
    :shade="true"
    :shade-close="false"
    :move="true"
    :resize="true"
  >
    <div class="order-detail-dialog" v-loading="loading">
      <div v-if="orderDetail" class="order-content">
        <!-- 订单基本信息 -->
        <lay-card class="info-card">
          <template #header>
            <h3>订单基本信息</h3>
          </template>
          <div class="order-basic-info">
            <lay-row :space="24">
              <lay-col :md="8">
                <div class="info-item">
                  <label>订单号：</label>
                  <span class="order-no">{{ orderDetail.orderNo }}</span>
                  <lay-button size="xs" @click="copyOrderNo" style="margin-left: 8px;">复制</lay-button>
                </div>
              </lay-col>
              <lay-col :md="8">
                <div class="info-item">
                  <label>订单状态：</label>
                  <lay-tag :type="getOrderStatusType(orderDetail.orderStatus)">
                    {{ getOrderStatusText(orderDetail.orderStatus) }}
                  </lay-tag>
                </div>
              </lay-col>
              <lay-col :md="8">
                <div class="info-item">
                  <label>支付状态：</label>
                  <lay-tag :type="orderDetail.paymentStatus === 1 ? 'normal' : 'warm'">
                    {{ orderDetail.paymentStatus === 1 ? '已支付' : '未支付' }}
                  </lay-tag>
                </div>
              </lay-col>
            </lay-row>
            <lay-row :space="24" style="margin-top: 16px;">
              <lay-col :md="8">
                <div class="info-item">
                  <label>物流状态：</label>
                  <lay-tag :type="getShippingStatusType(orderDetail.shippingStatus)">
                    {{ getShippingStatusText(orderDetail.shippingStatus) }}
                  </lay-tag>
                </div>
              </lay-col>
              <lay-col :md="8">
                <div class="info-item">
                  <label>支付方式：</label>
                  <span>{{ getPaymentMethodText(orderDetail.paymentMethod) }}</span>
                </div>
              </lay-col>
              <lay-col :md="8">
                <div class="info-item">
                  <label>创建时间：</label>
                  <span>{{ formatDateTime(orderDetail.createdAt) }}</span>
                </div>
              </lay-col>
            </lay-row>
            <lay-row :space="24" style="margin-top: 16px;" v-if="orderDetail.paymentTime">
              <lay-col :md="8">
                <div class="info-item">
                  <label>支付时间：</label>
                  <span>{{ formatDateTime(orderDetail.paymentTime) }}</span>
                </div>
              </lay-col>
              <lay-col :md="8" v-if="orderDetail.shippingTime">
                <div class="info-item">
                  <label>发货时间：</label>
                  <span>{{ formatDateTime(orderDetail.shippingTime) }}</span>
                </div>
              </lay-col>
              <lay-col :md="8" v-if="orderDetail.confirmTime">
                <div class="info-item">
                  <label>完成时间：</label>
                  <span>{{ formatDateTime(orderDetail.confirmTime) }}</span>
                </div>
              </lay-col>
            </lay-row>
          </div>
        </lay-card>

        <!-- 收货人信息 -->
        <lay-card class="info-card">
          <template #header>
            <h3>收货人信息</h3>
          </template>
          <div class="consignee-info">
            <lay-row :space="24">
              <lay-col :md="8">
                <div class="info-item">
                  <label>收货人：</label>
                  <span>{{ orderDetail.consigneeName }}</span>
                </div>
              </lay-col>
              <lay-col :md="8">
                <div class="info-item">
                  <label>联系电话：</label>
                  <span>{{ orderDetail.consigneePhone }}</span>
                </div>
              </lay-col>
              <lay-col :md="8">
                <div class="info-item">
                  <label>收货地址：</label>
                  <span>{{ orderDetail.consigneeAddress || '-' }}</span>
                </div>
              </lay-col>
            </lay-row>
            <lay-row style="margin-top: 16px;">
              <lay-col :md="24">
                <div class="info-item">
                  <label>收货地址：</label>
                  <span>{{ getFullAddress(orderDetail) }}</span>
                </div>
              </lay-col>
            </lay-row>
          </div>
        </lay-card>

        <!-- 商品信息 -->
        <lay-card class="info-card">
          <template #header>
            <h3>商品信息</h3>
          </template>
          <lay-table 
            :columns="itemColumns" 
            :data-source="orderDetail.items || []"
            :pagination="false"
          >
            <template #productInfo="{ row }">
              <div class="product-info">
                <img 
                  :src="row.productImage || '/placeholder.jpg'" 
                  :alt="row.productName"
                  class="product-image"
                  @error="handleImageError"
                />
                <div class="product-details">
                  <div class="product-name">{{ row.productName }}</div>
                  <div class="product-sku" v-if="row.skuSpecifications">规格: {{ formatSpecifications(row.skuSpecifications) }}</div>
                </div>
              </div>
            </template>

            <template #price="{ row }">
              <div class="price-info">
                <div class="current-price">¥{{ formatAmount(row.price) }}</div>
              </div>
            </template>

            <template #total="{ row }">
              <span class="total-amount">¥{{ formatAmount(row.totalAmount) }}</span>
            </template>
          </lay-table>
        </lay-card>

        <!-- 费用明细 -->
        <lay-card class="info-card">
          <template #header>
            <h3>费用明细</h3>
          </template>
          <div class="cost-detail">
            <div class="cost-item">
              <span class="cost-label">商品总额：</span>
              <span class="cost-value">¥{{ formatAmount(orderDetail.goodsAmount) }}</span>
            </div>
            <div class="cost-item" v-if="orderDetail.pointsAmount > 0">
              <span class="cost-label">积分抵扣：</span>
              <span class="cost-value discount">-¥{{ formatAmount(orderDetail.pointsAmount) }}</span>
            </div>
            <div class="cost-item">
              <span class="cost-label">运费：</span>
              <span class="cost-value">¥{{ formatAmount(orderDetail.shippingFee) }}</span>
            </div>
            <div class="cost-item total">
              <span class="cost-label">订单总额：</span>
              <span class="cost-value">¥{{ formatAmount(orderDetail.totalAmount) }}</span>
            </div>
          </div>
        </lay-card>

        <!-- 物流信息 -->
        <lay-card class="info-card" v-if="orderDetail.shipping_status > 0">
          <template #header>
            <h3>物流信息</h3>
          </template>
          <div class="shipping-info">
            <lay-row :space="24" v-if="orderDetail.shipping_company || orderDetail.tracking_number">
              <lay-col :md="12">
                <div class="info-item">
                  <label>物流公司：</label>
                  <span>{{ orderDetail.shipping_company || '-' }}</span>
                </div>
              </lay-col>
              <lay-col :md="12">
                <div class="info-item">
                  <label>快递单号：</label>
                  <span class="tracking-number">{{ orderDetail.tracking_number || '-' }}</span>
                  <lay-button 
                    v-if="orderDetail.tracking_number" 
                    size="xs" 
                    @click="copyTrackingNumber" 
                    style="margin-left: 8px;"
                  >
                    复制
                  </lay-button>
                </div>
              </lay-col>
            </lay-row>
            <div v-if="orderDetail.shipping_notes" style="margin-top: 16px;">
              <div class="info-item">
                <label>物流备注：</label>
                <span>{{ orderDetail.shipping_notes }}</span>
              </div>
            </div>
          </div>
        </lay-card>

        <!-- 订单日志 -->
        <lay-card class="info-card" v-if="orderLogs.length > 0">
          <template #header>
            <h3>订单日志</h3>
          </template>
          <div class="order-logs">
            <lay-timeline>
              <lay-timeline-item 
                v-for="log in orderLogs" 
                :key="log.id"
                :title="log.action"
              >
                <div class="log-content">
                  <div class="log-description">{{ log.description }}</div>
                  <div class="log-meta">
                    <span class="log-operator" v-if="log.operator">操作人: {{ log.operator }}</span>
                    <span class="log-time">{{ formatDateTime(log.created_at) }}</span>
                  </div>
                </div>
              </lay-timeline-item>
            </lay-timeline>
          </div>
        </lay-card>

        <!-- 备注信息 -->
        <lay-card class="info-card" v-if="orderDetail.notes">
          <template #header>
            <h3>备注信息</h3>
          </template>
          <div class="notes-content">
            <p>{{ orderDetail.notes }}</p>
          </div>
        </lay-card>
      </div>

      <!-- 操作按钮 -->
      <div class="dialog-footer">
        <lay-button @click="handleClose">关闭</lay-button>
        <lay-button 
          v-if="orderDetail?.orderStatus === 2 && orderDetail?.paymentStatus === 1" 
          type="primary" 
          @click="handleShip"
        >
          发货
        </lay-button>
        <lay-button 
          v-if="orderDetail?.orderStatus === 1" 
          type="warm" 
          @click="handleCancel"
        >
          取消订单
        </lay-button>
      </div>
    </div>
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { layer } from '@layui/layer-vue'
import { orderApi, type OrderDetail, type OrderLog } from '@/api/module/order'

interface Props {
  visible: boolean
  orderId: number | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const orderDetail = ref<OrderDetail | null>(null)
const orderLogs = ref<OrderLog[]>([])

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 商品列表表格配置
const itemColumns = [
  {
    title: '商品信息',
    key: 'productInfo',
    customSlot: 'productInfo',
    width: 300
  },
  {
    title: '单价',
    key: 'price',
    customSlot: 'price',
    width: 120
  },
  {
    title: '数量',
    key: 'quantity',
    width: 80
  },
  {
    title: '小计',
    key: 'total',
    customSlot: 'total',
    width: 120
  }
]

// 监听订单ID变化
watch(() => props.orderId, (newId) => {
  if (newId && props.visible) {
    getOrderDetail(newId)
  }
}, { immediate: true })

// 监听对话框显示状态
watch(() => props.visible, (newVisible) => {
  if (newVisible && props.orderId) {
    getOrderDetail(props.orderId)
  }
})

// 获取订单详情
const getOrderDetail = async (orderId: number) => {
  try {
    loading.value = true
    const detailResponse = await orderApi.getOrderDetail(orderId)

    if (detailResponse.code === 200) {
      orderDetail.value = detailResponse.data
    }

    // 暂时清空订单日志，等待后端接口实现
    orderLogs.value = []
  } catch (error) {
    console.error('获取订单详情失败:', error)
    layer.msg('获取订单详情失败', { icon: 2 })
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  orderDetail.value = null
  orderLogs.value = []
}

// 发货
const handleShip = () => {
  // 触发父组件的发货操作
  emit('refresh')
  layer.msg('请在发货对话框中操作', { icon: 0 })
}

// 取消订单
const handleCancel = async () => {
  if (!orderDetail.value) return

  try {
    const confirm = await layer.confirm('确定要取消这个订单吗？', {
      title: '确认取消',
      icon: 3
    })
    
    if (confirm) {
      const response = await orderApi.cancelOrder(orderDetail.value.id)
      if (response.code === 200) {
        layer.msg('订单取消成功', { icon: 1 })
        emit('refresh')
        getOrderDetail(orderDetail.value.id) // 刷新详情
      }
    }
  } catch (error) {
    console.error('取消订单失败:', error)
    layer.msg('取消订单失败', { icon: 2 })
  }
}

// 打印订单
const handlePrint = () => {
  // TODO: 实现打印功能
  layer.msg('打印功能开发中', { icon: 0 })
}

// 复制订单号
const copyOrderNo = async () => {
  if (!orderDetail.value) return
  try {
    await navigator.clipboard.writeText(orderDetail.value.orderNo)
    layer.msg('订单号已复制', { icon: 1 })
  } catch (error) {
    layer.msg('复制失败', { icon: 2 })
  }
}

// 复制快递单号
const copyTrackingNumber = async () => {
  if (!orderDetail.value?.deliveryNo) return
  try {
    await navigator.clipboard.writeText(orderDetail.value.deliveryNo)
    layer.msg('快递单号已复制', { icon: 1 })
  } catch (error) {
    layer.msg('复制失败', { icon: 2 })
  }
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/placeholder.jpg'
}

// 获取完整地址
const getFullAddress = (order: OrderDetail) => {
  return order.consigneeAddress || '-'
}

// 格式化商品规格
const formatSpecifications = (specifications: any) => {
  if (!specifications || typeof specifications !== 'object') return ''
  return Object.entries(specifications).map(([key, value]) => `${key}: ${value}`).join(', ')
}

// 格式化金额
const formatAmount = (amount: number | string) => {
  const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount
  return numAmount?.toFixed(2) || '0.00'
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
  const statusMap = {
    1: 'warm',     // 待付款
    2: 'normal',   // 待发货
    3: 'primary',  // 待收货
    4: 'normal',   // 已完成
    5: 'danger',   // 已取消
    6: 'warm'      // 退款中
  }
  return statusMap[status] || 'primary'
}

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  const statusMap = {
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '已完成',
    5: '已取消',
    6: '退款中'
  }
  return statusMap[status] || '未知'
}

// 获取物流状态类型
const getShippingStatusType = (status: number) => {
  const statusMap = {
    0: 'warm',     // 未发货
    1: 'primary',  // 已发货
    2: 'normal'    // 已收货
  }
  return statusMap[status] || 'primary'
}

// 获取物流状态文本
const getShippingStatusText = (status: number) => {
  const statusMap = {
    0: '未发货',
    1: '已发货',
    2: '已收货'
  }
  return statusMap[status] || '未知'
}

// 获取支付方式文本
const getPaymentMethodText = (method: number) => {
  const methodMap = {
    1: '支付宝',
    2: '微信支付',
    3: '银行卡'
  }
  return methodMap[method] || '未知'
}
</script>

<style scoped>
.order-detail-dialog {
  padding: 20px;
  max-height: 80vh;
  overflow-y: auto;
}

.order-content {
  margin-bottom: 20px;
}

.info-card {
  margin-bottom: 20px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
}

.info-card h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.order-basic-info,
.consignee-info,
.shipping-info {
  padding: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-item label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  margin-right: 8px;
}

.order-no,
.tracking-number {
  font-family: monospace;
  font-weight: 500;
  color: #1890ff;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e6e6e6;
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  line-height: 1.4;
}

.product-sku {
  font-size: 12px;
  color: #666;
}

.price-info {
  text-align: right;
}

.current-price {
  font-weight: 600;
  color: #f56c6c;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
  margin-top: 2px;
}

.total-amount {
  font-weight: 600;
  color: #f56c6c;
}

.cost-detail {
  padding: 16px;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.cost-item:last-child {
  border-bottom: none;
}

.cost-item.total {
  font-weight: 600;
  font-size: 16px;
  color: #f56c6c;
  border-top: 2px solid #e6e6e6;
  margin-top: 8px;
  padding-top: 16px;
}

.cost-label {
  color: #666;
}

.cost-value {
  color: #333;
}

.cost-value.discount {
  color: #52c41a;
}

.order-logs {
  padding: 16px;
}

.log-content {
  margin-top: 8px;
}

.log-description {
  color: #333;
  margin-bottom: 4px;
}

.log-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
}

.notes-content {
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin: 16px;
}

.notes-content p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 20px;
  border-top: 1px solid #e6e6e6;
}

@media (max-width: 768px) {
  .order-detail-dialog {
    padding: 12px;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .info-item label {
    min-width: auto;
    margin-bottom: 4px;
  }
  
  .product-info {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .dialog-footer {
    flex-wrap: wrap;
  }
}
</style>